package com.zg.assistant.web;

import com.alibaba.fastjson.JSON;
import com.zg.assistant.req.ClientSendMsgReq;
import com.zg.assistant.service.CommunicationService;
import com.zg.common.core.R;
import com.zg.common.core.User;
import com.zg.common.web.Req;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Map;

/**
* @author zg
*/
@RestController
@RequiredArgsConstructor
@Slf4j
public class CommunicationController {

	private final CommunicationService communicationService;

	/**
	 * 发送消息
	 * @param param 消息参数
	 * @return 结果
	 */
	@PostMapping("/communication/client/send")
	public R<?> clientSendMsg(@RequestBody @Valid ClientSendMsgReq param) {
		User user = Req.getCurrUser();
		if (user == null) {
			return R.error("未登录");
		}

		// 获取发送者信息
		String userName = user.getUsername();

		// 发送消息
		boolean result = communicationService.sendWebSocketMessage(param.getContent(), param.getUuid(), userName);

		if (result) {
			return R.success("消息发送成功");
		} else {
			return R.error("消息发送失败，接收方可能不在线");
		}
	}

	/**
	 * 小助手回调接口
	 * @param params 消息参数(Map格式)
	 * @return 结果
	 */
	@PostMapping("/communication/assistant/send")
	public R<?> assistantSendMsg(@RequestBody Map<String, Object> params) {
		log.info("接收到小助手回调请求: {}", JSON.toJSONString(params));

		try {
			// 参数校验
			if (params == null) {
				return R.error("请求参数不能为空");
			}

			// 必填字段校验
			if (ObjectUtils.isEmpty(params.get("channelId"))) {
				return R.error("通道id不能为空");
			}
			if (ObjectUtils.isEmpty(params.get("showClient"))) {
				return R.error("效果展示客户端不能为空");
			}
			if (ObjectUtils.isEmpty(params.get("order"))) {
				return R.error("指令不能为空");
			}

			// 直接使用Map发送WebSocket消息
			boolean result = communicationService.sendWebSocketJsonMessage(params);

			if (result) {
				return R.success("小助手发送消息成功");
			} else {
				return R.error("小助手发送消息失败，接收方可能不在线");
			}
		} catch (Exception e) {
			log.error("小助手回调处理异常", e);
			return R.error("处理异常: " + e.getMessage());
		}
	}
}
